/*
 * glShadow.cpp
 *
 *  Created on: 28.10.2012
 *      Author: Martin
 */

#ifdef _WIN32 
#include <windows.h> 
#endif

#include "glShadow.h"

glShadow::glShadow(int _mapSize, float _step)
{
	mapSize = _mapSize;
	step = _step;

	FramebufferName = 0;
	depthTexture = 0;

	// set view matrix in world look to the centre of map
	World::world->setShadowView(
			glm::vec3((mapSize * step) / 2, 0.0, (mapSize * step) / 2));

	// The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer.

	glGenFramebuffers(1, &FramebufferName);
	glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);

	// Depth texture. Slower than a depth buffer, but you can sample it later in your shader

	glGenTextures(1, &depthTexture);
	glBindTexture(GL_TEXTURE_2D, depthTexture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, SHADOW_MAP_SIZE,
			SHADOW_MAP_SIZE, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE,
			GL_COMPARE_R_TO_TEXTURE);

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
			depthTexture, 0);

	// No color output in the bound framebuffer, only depth.
	glDrawBuffer(GL_NONE);

	// Always check that our framebuffer is ok
	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
		std::cerr << "Unable to use frame buffer.\n" << std::endl;

}

glShadow::~glShadow()
{
	// delete buffer
	glDeleteBuffers(1, &FramebufferName);

	// delete depth texture
	glDeleteTextures(1, &depthTexture);
}

void glShadow::glShadowBegin()
{
	glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);

	// change view port
	glViewport(0, 0, SHADOW_MAP_SIZE, SHADOW_MAP_SIZE);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

GLuint glShadow::glShadowEnd()
{
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glClear(GL_DEPTH_BUFFER_BIT);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// set view port back to screen
	glViewport(0, 0, Engine::screenSettings.screenWidth,
			Engine::screenSettings.screenHeight);

	// stop shader
	glUseProgram(0);

	return depthTexture;
}

